package com.example.fang.demodruid.concurency3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyTest1 {

    private Lock lock=new ReentrantLock(); //可重入锁

    public  static void   main(String[] args){
        MyTest1 myTest1=new MyTest1();
        Thread t1=new Thread(()->{
              for(int i=0;i<10;i++){
                  myTest1.mymethod1();
                  try {
                      Thread.sleep(2000);
                  }catch (Exception e){
                      e.printStackTrace();
                  }
              }

        });
        Thread t2=new Thread(()->{
            for(int i=0;i<10;i++){
                myTest1.mymethod2();
                try {
                    Thread.sleep(300);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        });
        t1.start();
        t2.start();


    }
    public void mymethod1(){
        try {
            lock.lock();
            System.out.println("myMethod1 invoked");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    public void mymethod2(){
     /*   try {
            lock.lock();
            System.out.println("myMethod2 invoked");
        }catch (Exception e){
           e.printStackTrace();
        }finally {
            lock.unlock();
        }*/
        boolean result=false;
        try {
            result=lock.tryLock(800, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (result){
            System.out.println("get the lock");
        }else{
            System.out.println("can't get the lock");
        }
    }

}
